/*
 * @Author: jack_yang98 1246900429@qq.com
 * @Date: 2024-08-04 22:59:54
 * @LastEditors: jack_yang98 1246900429@qq.com
 * @LastEditTime: 2024-08-04 23:48:04
 * @FilePath: /gateway/app/app_router.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "app_router.h"
#include "app_mqtt.h"
#include "app_message.h"
#include "thirdparty/log/log.h"
#include "string.h"
#define MAX_DEVICE_NUM 10

static Device *devices[MAX_DEVICE_NUM];
static int device_num = 0;

static int App_router_mqttCallback(char *json_str, int len)
{
    unsigned char buf[1024];
    // 将数据转换为二进制
    int rc;
    Message message;
    rc = App_message_initByJson(&message, json_str, len);
    if (rc < 0)
    {
        log_error("App_message_initByJson failed");
        App_message_free(&message);
        return -1;
    }

    rc = App_message_saveBinary(&message, buf, 1024);

    App_message_free(&message);
    if (rc < 0)
    {
        log_error("App_message_saveBinary failed");
    }

    // 写入设备
    for (int i = 0; i < device_num; i++)
    {
        if ((int)buf[0] == devices[i]->connection_type)
        {

            return App_device_write(devices[i], buf, rc);
        }
    }

    log_error("App_router_mqttCallback : 未找到设备");
    return -1; 
}

static int App_router_deviceCallback(void *put, int len)
{
    char buf[1024];
    Message message;
    if (App_message_initByBinary(&message, put, len) != 0)
    {
        log_error("App_message_initByBinary failed");
        return -1;
    }

    int rc = App_message_saveJson(&message, buf, sizeof(buf));

    App_message_free(&message);

    if (rc < 0)
    {
        log_error("App_message_saveJson failed");
        return -1;
    }
    
    return App_mqtt_send(buf, strlen(buf));
    
}

int App_router_init()
{
    int rc;
    rc = App_mqtt_init();
    if (rc != 0)
    {
        log_error("App_mqtt_init failed");
        return -1;
    }
    App_mqtt_reisterRecvCallback(App_router_mqttCallback);

    log_debug("App_router_init success");
    return 0;
}

int App_router_registerDevice(Device *device)
{
    devices[device_num++] = device;
    App_device_registerRecvCallback(device, App_router_deviceCallback);
    App_device_start(device);
    return 0;
}

void App_router_close()
{
    for (int i = 0; i < device_num; i++)
    {
        App_device_stop(devices[i]);
        App_device_close(devices[i]);
    }

    App_mqtt_close();
}
